package com.android.IMpulse;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.net.UnknownHostException;

import com.example.android.networkusage.NetworkActivity.DownloadXmlTask;
import com.example.android.networkusage.NetworkActivity.NetworkReceiver;
import com.example.impulse.R;
import com.example.impulse.R.layout;
import com.example.impulse.R.menu;
import com.mekya.Login;
import com.mekya.SignUp;
import com.mekya.interfaces.IAppManager;
import com.mekya.services.IMService;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class MainActivity extends Activity {
	private static final String URL = "http://abc.com";

	private IMpulseService iMpulseService;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeInfo = connMgr.getActiveNetworkInfo();
		if (activeInfo != null && activeInfo.isConnected()) {
			wifiConnected = activeInfo.getType() == ConnectivityManager.TYPE_WIFI;
			mobileConnected = activeInfo.getType() == ConnectivityManager.TYPE_MOBILE;
			new RequestServerConnectionTask().execute(URL);
		} else {
			wifiConnected = false;
			mobileConnected = false;
		}

		// Register BroadcastReceiver to track connection changes.
		IntentFilter filter = new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION);
		receiver = new NetworkReceiver();
		this.registerReceiver(receiver, filter);

	}

	private class RequestServerConnectionTask extends AsyncTask {
		@Override
		protected String doInBackground(String... urls) {
			try {
				return requestServerConnection(urls[0]);
			} catch (IOException e) {
				return "Unable to retrieve web page. URL may be invalid.";
			}
		}

		@Override
		protected void onPostExecute(String result) {
			if (SERVER_CONNECTED == result) {
				startListUpdate();
			}
			else if(SIGN_UP == result) {
				
			}
			
		}
	}

	bool requestServerConnection(String urlString) {
		try {
			String[] str = ip.split("\\.");
			byte[] IP = new byte[str.length];
			for (int i = 0; i < str.length; i++) {
				IP[i] = (byte) Integer.parseInt(str[i]);				
			}
			Socket socket = getSocket(InetAddress.getByAddress(IP), port);
			if (socket == null) {
				return false;
			}
			PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
			String message = username + " " + GET_SERVER_CONNECTION;
			out.println(username + " " + GET_SERVER_CONNECTION);
		} catch (UnknownHostException e) {			
			return false;
			//e.printStackTrace();
		} catch (IOException e) {
			return false;			
			//e.printStackTrace();
		}
		
		return true;	
	}

	/**
	 * 
	 * This BroadcastReceiver intercepts the
	 * android.net.ConnectivityManager.CONNECTIVITY_ACTION, which indicates a
	 * connection change. It checks whether the type is TYPE_WIFI. If it is, it
	 * checks whether Wi-Fi is connected and sets the wifiConnected flag in the
	 * main activity accordingly.
	 * 
	 */
	public class NetworkReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			ConnectivityManager connMgr = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

			if (WIFI.equals(sPref) && networkInfo != null
					&& networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
				if(wifiConnected == false && mobileConnected == false)
				{
					new RequestServerConnectionTask().execute(URL);
					wifiConnected == true;
				}

			} else if (ANY.equals(sPref) && networkInfo != null) {
				if(wifiConnected == false && mobileConnected == false)
				{
					new RequestServerConnectionTask().execute(URL);
					wifiConnected == true;
					mobileConnected == true;
				}

			} else {
				Toast.makeText(context, R.string.lost_connection,
						Toast.LENGTH_SHORT).show();
			}
		}
	}

}
